package org.artifact.core.actor;

import cn.hutool.core.thread.ThreadUtil;
import cn.hutool.log.Log;
import cn.hutool.log.LogFactory;
import co.paralleluniverse.actors.ActorRegistry;
import co.paralleluniverse.actors.behaviors.Server;
import co.paralleluniverse.common.util.CheckedCallable;
import co.paralleluniverse.fibers.FiberAsync;
import co.paralleluniverse.fibers.SuspendExecution;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;

public class ActorHelper {

    private static final Log log = LogFactory.get(ActorHelper.class);

    static Map<String, Server> actors = new ConcurrentHashMap<>();

    public static Server getActor(String name) {
//        return actors.computeIfAbsent(name, k -> new GameActor(new ActorHandler()).spawn());
        try {
            return (Server) ActorRegistry.getOrRegisterActor(name, ()->new GameActor(new ActorHandler()));
        } catch (Exception e) {
            log.error(e);
        }
        return null;
    }

    /**
     * 同步请求
     */
    public static <T> T call(Server server, ICallable callable) throws SuspendExecution, InterruptedException {
        return (T) server.call(callable);
    }

//    /**
//     * 异步请求
//     *
//     * @param server
//     * @param runnable
//     * @throws SuspendExecution
//     * @throws InterruptedException
//     */
//    public static void cast(Server server, IRunnable runnable) throws SuspendExecution {
//        server.cast(runnable);
//    }


    public static void send(Server server, IRunnable runnable) {
        server.trySend(runnable);
    }

    static ExecutorService executorService = ThreadUtil.newExecutor(10);

    public static <T> T runBlocking(CheckedCallable callable) throws InterruptedException, SuspendExecution {
        return (T) FiberAsync.runBlocking(executorService, callable);
    }
}
